﻿namespace MINERP.NewPB.Forms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Windows.Forms;

    using MINERP.COM;
    using MINERP.MODEL.FoundationModel;
    using MINERP.MODEL.NewPinBan;
    using MINERP.NewPB.Presenter;


    public partial class FrmAutoPinban
    {
        private List<DisPalyBoardInfo> wasteArr = new List<DisPalyBoardInfo>();
       
        private static object threadid = new object();
        public void StartPBss()
        {
            //if (cancellationTokenSource != null) {
            //    cancellationTokenSource.Cancel();
            //}
            //cancellationTokenSource = ThreadEx.StartRotation(cmdPB, 2000, 3000, true, threadid);
            Thread thredPb = new Thread(new ThreadStart(cmdPB));
            thredPb.Start();
            m_SyncContext.Send(c => progressBar1.Style = ProgressBarStyle.Marquee, null);
            MaxOrderInfoNum = _AutoPinBanBll.GridQty(DataTransfer.CurPrinter.PrinterID);
        }
        private void cmdPB()
        {

            Tb_paperTemplate_Info outBoardTemplete;
            m_SyncContext.Send(c =>
            {
                simpleButtonStartEnd.Text = "停止";
                WriteText("准备退版重试");
                List<DisPalyBoardInfo> list = ((List<DisPalyBoardInfo>)gridControlBoard.DataSource).Where(p => p.Selected).ToList();
                List<int> BoardIDList = list.Select(p => p.BoardID).ToList();
                int val = _AutoPinBanBll.DeleteBoards(BoardIDList);
                BangDingUnsure();
                WriteText("尝试重新拼版");
            }, null);
            wasteStands = Convert.ToDecimal(textEditMaxWaste.Text) / 100;
            _AutoPinBanBll.BARCODEWIDTH2 = DataTransfer.BarCodePixWidth;
            ClearWaste = Convert.ToDecimal(txtClearWaste.Text) / 100;
            int occPB = Convert.ToInt32(txtOCCPB.Text);
            int occClearPB = Convert.ToInt32(txtOCCClearPB.Text);
            int step = 0;
            if (occPB > occClearPB)
            {
                occClearPB = occPB;
            }
            else
            {
                decimal s = occClearPB - occPB;
                step = (int)Math.Floor(s * 0.1M);
                if (step <= 1)
                {
                    step = 1;
                }
            }
            //				int cellQty = (int) Math.Floor(MaxOrderInfoNum*occPB);
            int cellQty = occPB;
            List<PhotoInfo_PinBan> listResult;
            decimal outWaste = 0;
            int currLength;
            DateTime stTime = DateTime.Now;
            PBINFO();
            while (!DataTransfer.cancellation.IsStopRequired)
            {
                //获取要拼版的照片在数据库中查找 前20个产品的照片获取规则：1已经拼过的产品2加急产品3开单时间
                //				backgroundWorkerAutoPinBan.ReportProgress(1, "正在获取要拼版的照片");
                PostInfo(1, "正在获取要拼版的照片");
                List<PhotoInfo_PinBan> sourceList = _AutoPinBanBll.GetWaitPBPhotoList(DataTransfer.curTemplate, DataTransfer.CurPrinter.PrinterID,
                                                                                    cellQty);
                if (DataTransfer.cancellation.IsStopRequired)
                {
                    m_SyncContext.Send(c =>
                    {
                        simpleButtonStartEnd.Text = "开始";
                    }, null);
                    return;
                }
                isNeedSmallPic = false;
                listResult = _AutoPinBanBll.AutoPinSN(sourceList, listTemp, DataTransfer.CurPrinter, out outWaste, out currLength, MinBoardLengthPre, 0,
                                                    out outBoardTemplete);
                listResult.ForEach(each => {
                    if (each.BarCodeStatus == 0)
                    {
                        each.BarCodeStatus = 1;
                    }
                    else if ((each.BarCodeStatus == 1))
                    {
                        each.BarCodeStatus = 0;
                    }
                });
                if (DataTransfer.cancellation.IsStopRequired)
                {
                    m_SyncContext.Send(c =>
                    {
                        simpleButtonStartEnd.Text = "开始";
                    }, null);
                    return;
                }
                while (outWaste > wasteStands)
                {
                    cellQty += step;
                    if (cellQty > occClearPB)
                    {
                        //到达清柜值
                        if (outWaste <= ClearWaste)
                        {
                            PostInfo(-1, string.Format("获取产品数已超出清格值 按清柜浪费率出版 浪费率 {0:F2}", outWaste * 100));
                            break;
                        }
                        else
                        {
                            m_SyncContext.Send(c => MessageBox.Show(string.Format("浪费率超过清格浪费率需手动拼版 当前版浪费率 {0:F2}", outWaste * 100)), null);
                            //						thread.Abort();
                            return;
                        }
                    }
                    else
                    {
                        PostInfo(-1, string.Format("未满足拼版浪费率 {0:F2} 照片数:{1} 尝试按 {2} 格 重新获取照片...", outWaste * 100, sourceList.Count, cellQty));
                        //按新增加的格子数重新拼版
                        sourceList = _AutoPinBanBll.GetWaitPBPhotoList(DataTransfer.curTemplate, DataTransfer.CurPrinter.PrinterID, cellQty);
                        listResult = _AutoPinBanBll.AutoPinSN(sourceList, listTemp, DataTransfer.CurPrinter, out outWaste, out currLength, MinBoardLengthPre, 0,
                                                            out outBoardTemplete);
                        listResult.ForEach(each =>
                        {
                            if (each.BarCodeStatus == 0)
                            {
                                each.BarCodeStatus = 1;
                            }
                            else if ((each.BarCodeStatus == 1))
                            {
                                each.BarCodeStatus = 0;
                            }
                        });
                        if (DataTransfer.cancellation.IsStopRequired)
                        {
                            m_SyncContext.Send(c =>
                            {
                                simpleButtonStartEnd.Text = "开始";
                            }, null);
                            return;
                        }
                    }
                }
                if (listResult != null)
                {
                    if ((CheckPhoto(listResult)) || outWaste < 0 || outWaste == 1 || listResult.Count == 0)
                    {
                        listResult.ForEach(p => p.IsInBoard = false);
                        IsDoing = false;

                        PostInfo(6, "无照片可用已暂停...");
                        return;
                    }
                    else
                    {
                        if (DataTransfer.cancellation.IsStopRequired)
                        {
                            m_SyncContext.Send(c =>
                            {
                                simpleButtonStartEnd.Text = "开始";
                            }, null);
                            return;
                        }
                        int Boardid = _NewPBBll.AutoCreateBoard(listResult, outBoardTemplete, DataTransfer.CurPrinter, UserID, (float)outWaste,
                                                                    currLength);
                        //添加成功
                        if (Boardid != null && Boardid > 10)
                        {
                            DisPalyBoardInfo board = new DisPalyBoardInfo();
                            board.BoardID = Boardid;
                            board.PhotoNum = listResult.Count();
                            board.UserfulNum = Math.Round(100 - outWaste * 100, 2);
                            board.Length = (decimal)Math.Round((double)currLength / DataTransfer.CurPrinter.PDPI * 2.54, 2);
                            board.UseTime = (decimal)(DateTime.Now - stTime).TotalSeconds;
                            board.listPhoto = listResult;
                            board.FactLength = currLength;
                            board.BoardTemplate = outBoardTemplete;
                            CurrBoardList.Add(board);
                            isNeedSmallPic = false;
                            PostInfo(3, "");
                            if (checkBoxMark.Checked)
                            {
                                //m_SyncContext.Send(c => _AutoPinBanBll.SaveBoards(new List<int>() {Boardid.BoardId}),1);
                                _AutoPinBanBll.SaveBoards(new List<int>() { Boardid });
                            }
                            wasteArr.Add(board);
                            if (DataTransfer.cancellation.IsStopRequired)
                            {
                                m_SyncContext.Send(c =>
                                {
                                    simpleButtonStartEnd.Text = "开始";
                                }, null);
                                return;
                            }
                            PBINFO();
                        }
                    }
                }
            }
        }
        private void PBINFO()
        {
            decimal SurplusArea, tArea;
            int UseCellQty;
            int PBTCellPhotoCount, PBSurplusPhotoCount;
            _AutoPinBanBll.GetPBInfo(DataTransfer.CurPrinter.PrinterID, DataTransfer.curTemplate.TempLateId, out SurplusArea, out UseCellQty,
                                    out tArea, out PBTCellPhotoCount, out PBSurplusPhotoCount);
            if (wasteArr.Count > 0)
            {
                decimal waste =
                    Convert.ToDecimal(wasteArr.Sum(c => c.UserfulNum) / wasteArr.Count);
                PBINFO(waste, tArea - SurplusArea, SurplusArea, UseCellQty, MaxOrderInfoNum, PBTCellPhotoCount, PBSurplusPhotoCount);
            }
            else
            {
                PBINFO(0, tArea - SurplusArea, SurplusArea, UseCellQty, MaxOrderInfoNum, PBTCellPhotoCount, PBSurplusPhotoCount);
            }
        }
    }

    
}
